<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="省名" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入省名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="市名" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入市名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区名" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入区名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="矿山名称" prop="mineName">
        <el-input
          v-model="queryParams.mineName"
          placeholder="请输入矿山名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceTypeId">
        <el-input
          v-model="queryParams.deviceTypeId"
          placeholder="请输入设备类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="安装时间" prop="installationTime">
        <el-date-picker
          clearable
          v-model="queryParams.installationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择安装时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上次维护时间" prop="lastMaintenanceTime">
        <el-date-picker
          clearable
          v-model="queryParams.lastMaintenanceTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上次维护时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input
          v-model="queryParams.longitude"
          placeholder="请输入经度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input
          v-model="queryParams.latitude"
          placeholder="请输入纬度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:device:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:device:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:device:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:device:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="deviceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备id" align="center" prop="deviceId" />
      <el-table-column label="省级" align="center" prop="province" />
      <el-table-column label="市级" align="center" prop="city" />
      <el-table-column label="区级" align="center" prop="location" />
      <el-table-column label="矿山名称" align="center" prop="mineName" />
      <el-table-column label="设备名" align="center" prop="deviceName" />
      <el-table-column label="设备类型" align="center" prop="deviceTypeId" />
      <el-table-column
        label="安装时间"
        align="center"
        prop="installationTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.installationTime, '{y}-{m}-{d}')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上次维护时间"
        align="center"
        prop="lastMaintenanceTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.lastMaintenanceTime, '{y}-{m}-{d}')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="省名" prop="province">
          <el-input v-model="form.province" placeholder="请输入省名" />
        </el-form-item>
        <el-form-item label="市名" prop="city">
          <el-input v-model="form.city" placeholder="请输入市名" />
        </el-form-item>
        <el-form-item label="区名" prop="location">
          <el-input v-model="form.location" placeholder="请输入区名" />
        </el-form-item>
        <el-form-item label="矿山名称" prop="mineName">
          <el-input v-model="form.mineName" placeholder="请输入矿山名称" />
        </el-form-item>
        <el-form-item label="设备名" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceTypeId">
          <el-input v-model="form.deviceTypeId" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="安装时间" prop="installationTime">
          <el-date-picker
            clearable
            v-model="form.installationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择安装时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上次维护时间" prop="lastMaintenanceTime">
          <el-date-picker
            clearable
            v-model="form.lastMaintenanceTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上次维护时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="charts-container">
      <div class="chart-container">
        <div ref="statusChart" style="width: 100%; height: 400px"></div>
      </div>
      <div class="mapWrapper">
        <el-button type="primary" @click="goBack" class="back-button"
          >返回上级</el-button
        >
        <div ref="mapChartRef" style="height: 400px; width: 100%"></div>
      </div>
    </div>
  </div>
</template>

<script setup name="Device">
import axios from 'axios';
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice
} from '@/api/system/device';

const { proxy } = getCurrentInstance();
const deviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const mapChartRef = ref();
const initChinaMap = ref();
const initAdCode = ref(100000); // 默认中国地图的编码
const currentMapName = ref('中国'); // 默认地图的名称
const mapList = ref([]); // 当前展示的省市区所有数据
const historyInfo = ref([]); // 记录历史点击的省市区，用于返回查询

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    province: null,
    city: null,
    location: null,
    mineName: null,
    deviceName: null,
    deviceTypeId: null,
    installationTime: null,
    lastMaintenanceTime: null,
    status: null,
    longitude: null,
    latitude: null
  },
  rules: {
    deviceName: [
      { required: true, message: '设备名不能为空', trigger: 'blur' }
    ],
    installationTime: [
      { required: true, message: '安装时间不能为空', trigger: 'blur' }
    ],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备管理列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listDevice(queryParams.value);
    deviceList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error('获取设备列表失败:', error);
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    deviceId: null,
    province: null,
    city: null,
    location: null,
    mineName: null,
    deviceName: null,
    deviceTypeId: null,
    installationTime: null,
    lastMaintenanceTime: null,
    status: null,
    longitude: null,
    latitude: null
  };
  proxy.resetForm('deviceRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList().then(() => {
    // 根据 queryParams 中的 province、city 来决定获取哪个级别的地图数据
    if (queryParams.value.city) {
      // 直接获取市级地图数据
      getMapDataByCity(queryParams.value.city);
    } else if (queryParams.value.province) {
      // 获取省级地图数据
      getMapDataByProvince(queryParams.value.province);
    } else if (queryParams.value.location) {
      // 如果只有区名，则保持当前地图，并高亮显示区名
      updateMapHighlight(queryParams.value.location);
    }
  });
}

// 更新地图高亮显示
const updateMapHighlight = (locationName) => {
  mapList.value.forEach((mapItem) => {
    mapItem.itemStyle = {
      areaColor: mapItem.name === locationName ? 'red' : '#CCEBEB'
    };
  });
  // 重新渲染地图
  renderChart(currentMapName.value, {
    features: mapList.value.map((mapItem) => ({ properties: mapItem }))
  });
};

// 根据省名获取地图数据
const getMapDataByProvince = async (provinceName) => {
  // 获取省的 adcode
  const province = mapList.value.find((item) => item.name === provinceName);
  if (province && province.adcode) {
    currentMapName.value = provinceName;
    getMapData(province.adcode);
  } else {
    console.error('未找到省名对应的 adcode');
  }
};

// 根据市名获取地图数据
const getMapDataByCity = async (cityName) => {
  // 获取市的 adcode
  const city = mapList.value.find((item) => item.name === cityName);
  if (city && city.adcode) {
    currentMapName.value = cityName;
    getMapData(city.adcode);
  } else {
    console.error('未找到市名对应的 adcode');
  }
};

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
  getMapData(initAdCode.value);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加设备管理';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _deviceId = row.deviceId || ids.value;
  getDevice(_deviceId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改设备管理';
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['deviceRef'].validate((valid) => {
    if (valid) {
      if (form.value.deviceId != null) {
        updateDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _deviceIds = row.deviceId || ids.value;
  proxy.$modal
    .confirm('是否确认删除设备管理编号为"' + _deviceIds + '"的数据项？')
    .then(function () {
      return delDevice(_deviceIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/device/export',
    {
      ...queryParams.value
    },
    `device_${new Date().getTime()}.xlsx`
  );
}

const statusChart = ref(null);
let chartInstance = null;

const statusCounts = ref({
  正常: 0,
  离线: 0,
  故障: 0
});

function initChart() {
  if (!chartInstance) {
    chartInstance = echarts.init(statusChart.value);
  }
  const option = {
    title: {
      text: '设备状态占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '状态',
        type: 'pie',
        radius: '50%',
        data: [
          {
            value: statusCounts.value.正常,
            name: '正常',
            itemStyle: { color: 'green' }
          },
          {
            value: statusCounts.value.离线,
            name: '离线',
            itemStyle: { color: 'yellow' }
          },
          {
            value: statusCounts.value.故障,
            name: '故障',
            itemStyle: { color: 'red' }
          }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chartInstance.setOption(option);
}

function updateStatusCounts() {
  statusCounts.value = {
    正常: 0,
    离线: 0,
    故障: 0
  };
  deviceList.value.forEach((device) => {
    if (device.status === '正常') {
      statusCounts.value.正常++;
    } else if (device.status === '离线') {
      statusCounts.value.离线++;
    } else if (device.status === '故障') {
      statusCounts.value.故障++;
    }
  });
  initChart();
}

// 获取地图数据
const getMapData = async (code) => {
  const data = await axios
    .get(`https://geo.datav.aliyun.com/areas_v3/bound/${code}_full.json`)
    .then((res) => {
      mapList.value = [];
      if (res.status === 200) {
        // 获取当前选中的省市区的所有名称和编码
        res.data.features.forEach((item) => {
          mapList.value.push(item.properties);
        });
        // 更新 mapList 的 itemStyle 根据 deviceList 中的 province
        mapList.value.forEach((mapItem) => {
          mapItem.itemStyle = {
            areaColor: deviceList.value.some(
              (device) =>
                device.province === mapItem.name ||
                device.city === mapItem.name ||
                device.location === mapItem.name
            )
              ? 'red'
              : '#CCEBEB'
          };
        });
        // 立即调用renderChart函数
        renderChart(currentMapName.value, res.data);
      }
    })
    .catch(() => {});
  return data;
};

// 渲染地图
const renderChart = (mapName, mapData) => {
  // 注册: registerMap('地图名称', 地图数据）, 地图名称须和option里面的map一致
  echarts.registerMap(mapName, mapData);

  // 地图配置项
  const option = {
    tooltip: {
      show: true,
      trigger: 'item',
      alwaysShowContent: false,
      backgroundColor: '#0C121C',
      borderColor: 'rgba(0, 0, 0, 0.16);',
      hideDelay: 100,
      triggerOn: 'mousemove',
      enterable: true,
      textStyle: {
        color: '#DADADA'
      },
      showDelay: 100,
      formatter: (params) => {
        return params.name;
      }
    },
    series: [
      {
        type: 'map',
        map: mapName, // 地图名称
        data: mapList.value.map((mapItem) => ({
          name: mapItem.name,
          value: 1,
          itemStyle: {
            areaColor: deviceList.value.some(
              (device) =>
                device.province === mapItem.name ||
                device.city === mapItem.name ||
                device.location === mapItem.name
            )
              ? 'red'
              : '#CCEBEB'
          }
        })),
        zoom: '1.1', // 当前视角的缩放比例
        label: {
          show: false // 是否显示省份名字
        },
        roam: false, // 是否开启缩放和平移
        itemStyle: {
          borderColor: '#F59A23', // 边界线颜色
          borderType: 'dashed' // 边界线类型
        },
        // 设置鼠标移上去高亮的样式
        emphasis: {
          itemStyle: {
            borderColor: '#34AEAE',
            areaColor: '#CCEBEB',
            borderType: 'solid'
          }
        }
      }
    ]
  };

  // 渲染
  initChinaMap.value.setOption(option);

  // 防止多次触发click事件，重要！！！
  initChinaMap.value.off('click');

  // 下钻
  initChinaMap.value.on('click', (params) => {
    const activeItem = mapList.value.find((item) => item.name == params.name);
    // 判断有子级的时候才可以下钻
    if (activeItem && activeItem.adcode && activeItem.childrenNum) {
      historyInfo.value.push(activeItem);
      currentMapName.value = params.name;
      getMapData(activeItem.adcode);
    }
  });
};

// 返回上一级
const goBack = () => {
  const lastItem = historyInfo.value.pop();
  if (lastItem && lastItem.parent && lastItem.parent.adcode) {
    getMapData(lastItem.parent.adcode);
  }
};

watch(deviceList, () => {
  updateStatusCounts();
  getMapData(initAdCode.value); // 重新获取和渲染地图数据
});

onMounted(async () => {
  await getList();
  initChinaMap.value = echarts.init(mapChartRef.value);
  getMapData(initAdCode.value);
});
</script>

<style scoped>
.charts-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.chart-container,
.mapWrapper {
  width: 48%;
}

.mapWrapper button {
  margin-bottom: 10px;
}

.chart-container {
  margin-right: 2%;
}

.mapWrapper {
  margin-left: 2%;
}

.back-button {
  margin-bottom: 10px;
  background-color: #409eff; /* 主题颜色 */
  border-color: #409eff; /* 边框颜色 */
  width: 20%; /* 按钮宽度 */
  padding: 10px 20px; /* 内边距 */
  font-size: 14px; /* 字体大小 */
  border-radius: 4px; /* 圆角 */
  transition: background-color 0.3s, border-color 0.3s; /* 过渡效果 */
}

.back-button:hover {
  background-color: #66b1ff; /* 鼠标悬停时的背景颜色 */
  border-color: #66b1ff; /* 鼠标悬停时的边框颜色 */
}

.back-button:active {
  background-color: #3a8ee6; /* 按下时的背景颜色 */
  border-color: #3a8ee6; /* 按下时的边框颜色 */
}
</style>
